package com.yape.webCrawler.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yape.annotation.CrawlerLog;
import com.yape.po.SectorFundFlow;
import com.yape.webCrawler.base.BaseCrawler;
import com.yape.webCrawler.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Hazuki
 * @Date 2025/5/24 上午10:03
 * @Version 1.0
 */
@Slf4j
@Component("sectorFundFlow")
public class SectorFundFlowCrawler extends BaseCrawler {

    // 涨幅最小的三个板块（跌幅最大）
    private static final String API_URL_BOTTOM = "https://push2.eastmoney.com/api/qt/clist/get?fid=f3&po=0&pz=3&pn=1&np=1&fltt=2&invt=1&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12,f14,f3";

    // 涨幅最大的三个板块
    private static final String API_URL_TOP = "https://push2.eastmoney.com/api/qt/clist/get?fid=f3&po=1&pz=3&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12,f14,f3";

    @Override
    @CrawlerLog
    public List<SectorFundFlow> execute() throws IOException {
        List<SectorFundFlow> resultList = new ArrayList<>();

        // 获取涨幅最大的三个板块
        List<SectorFundFlow> topThree = fetchSectors(API_URL_TOP);

        // 获取跌幅最大的三个板块
        List<SectorFundFlow> bottomThree = fetchSectors(API_URL_BOTTOM);

        // 合并两个列表
        resultList.addAll(topThree);
        resultList.addAll(bottomThree);

        // 日志输出
        log.info("============板块资金流数据============");
        log.info("涨幅最大的三个板块：");
        for (SectorFundFlow sector : topThree) {
            log.info(String.format("%-15s: %+.2f%%", sector.getSectorName(), sector.getDailyChangePercent()));
        }

        log.info("跌幅最大的三个板块：");
        for (SectorFundFlow sector : bottomThree) {
            log.info(String.format("%-15s: %+.2f%%", sector.getSectorName(), sector.getDailyChangePercent()));
        }

        return resultList;
    }

    private List<SectorFundFlow> fetchSectors(String apiUrl) throws IOException {
        String jsonpResponse = Jsoup.connect(apiUrl)
                .ignoreContentType(true)
                .execute()
                .body();

        String jsonResponse = JsonUtils.extractJsonFromJsonp(jsonpResponse);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        JsonNode diffList = rootNode.path("data").path("diff");

        List<SectorFundFlow> sectors = new ArrayList<>();

        // 解析JSON数据
        for (JsonNode item : diffList) {
            String code = item.path("f12").asText();
            String name = item.path("f14").asText();
            float percentage = (float) item.path("f3").asDouble();

            // 创建SectorFundFlow对象并保存到列表
            SectorFundFlow sector = SectorFundFlow.builder()
                    .sectorName(name)
                    .dailyChangePercent(percentage)
                    .build();

            sectors.add(sector);
        }

        return sectors;
    }

    @Override
    protected String getApiUrl() {
        // This method is not used anymore but kept for compatibility
        return API_URL_TOP;
    }
}